package logic

import (
	"context"
	"io"
	"net/http"
	"os"
	"path"
	"time"

	"portal/internal/common"
	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/types"
	"portal/tools/encryption"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stringx"
)

type UploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}


func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadLogic) Upload(r *http.Request) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	file,fileHeader,err := r.FormFile("file")
	if err != nil {
		return nil,errorx.NewBizError(500,err.Error())
	}
	defer file.Close()
	// 获取文件后缀
	filetype := path.Ext(fileHeader.Filename)
	if !stringx.Contains(common.AcceptFileSuffix,filetype) {
		return nil,errorx.NewBizError(500,"文件类型不正确")
	}
	if int64(common.MaxFileSize) < fileHeader.Size {
		return nil,errorx.NewBizError(500,"超出文件上传限制，请选择小于10mb的文件")
	}
	dir,err := encryption.EncryptionMd5(time.Now().String(),l.svcCtx.Config.Salt)
	if err != nil {
		return nil,errorx.NewBizError(500,err.Error())
	}
	fname,err := encryption.EncryptionMd5(fileHeader.Filename,l.svcCtx.Config.Salt)
	if err != nil {
		return nil,errorx.NewBizError(500,err.Error())
	}
	prefixUrl := common.BaseFileURI + dir
	if _, err := os.Stat(prefixUrl); os.IsNotExist(err) {
		err = os.Mkdir(prefixUrl, os.ModePerm)
		if err != nil {
			return nil,errorx.NewBizError(500,err.Error())
		}
	}
	// 创建文件 
	url := prefixUrl + "/" + fname + filetype
	newFile,err := os.Create(url)
	if err != nil {
		return nil,errorx.NewBizError(500,err.Error())
	}

	defer newFile.Close()

	_,err = io.Copy(newFile,file)
	if err != nil {
		return nil,errorx.NewBizError(500,err.Error())
	} 

	return &types.CommonResponse{
		Status: 200,
		Msg: "上传成功",
		Data: struct {
			Url string
		}{
			Url: "http://127.0.0.1:8888/download/" + dir + "/" + fname + filetype,
		},
	},nil
}
